<?php


namespace App\Http\Middleware;

use Closure;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class RequestLog
{
    public function handle($request, Closure $next)
    {
        //dump($request);die;
        $user = Auth::user();
        $req = [
            'admin_id'=>$user->id??'',
            'name'=>$user->nickname??'',
            'remote_addr' => $request->server()['REMOTE_ADDR']??'',
            'server_addr' => $request->server()['SERVER_ADDR']??'',
            'url' => $request->url(),
            'method' =>$request->method(),
            'params' => $request->all(),
        ];
        // 执行前记录请求信息
        Log::info('Request:', $req);

        $response = $next($request);


        if(isset($request->route()->action['as']) && $request->route()->action['as']){
            Log::info('Response:', ['content' => '查看日志']);
            return $response;
        }
        $content = $response->getContent();
        // 执行后记录响应信息
        Log::info('Response:', [
            'content' => $content,
        ]);

        $content = json_decode($content,true);
        if($content && $content['code']!==0){
            //企微报警
            $data = env('APP_ENV').'--pos: '.date('Y-m-d H:i:s').' '.$request->method().' '.$request->url().
                ' ;errMsg:'.$content['message'];

            Log::warning($data);
            $this->boot($data);
        }


        return $response;
    }


    private function boot($data)
    {
        $client = new \GuzzleHttp\Client();
        $url = env('WEBHOOK_URL');

        $res = $client->request('POST', $url, [
            'headers' => ['Content-Type' => 'application/json'],
            'json' => [
                'msgtype' => 'text',
                'text' => [
                    'content' => $data,
                ],
            ],
            'timeout' => 3,
        ]);
        $res = json_decode($res->getBody()->getContents(),true);
        if($res && $res['errcode']!=0){
            Log::error('机器人推送失败，status：'.$res['errcode'].'res:'.$res['errmsg']);
        }

        return true;
    }
}
